<?php
namespace app\admin\controller;
use think\facade\View;
use think\facade\Request;
use think\facade\Env;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Session;

class Clues extends Common{
    public $model;
    public function initialize()
    {
        parent::initialize();
//        $this->model=new \app\admin\model\Clues();
    }
    //线索列表
    public function index(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_customer')
                ->where(['status'=>0,'issuccess'=>-1])
                ->order('ut_time desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
              // 是否有查看手机号的权限
            // $userinfo = Db::name('admin')->where('username',$this->admin['username'])->find(); 
            // if ($userinfo['isphone'] == 0) {
            //     foreach ($list['data'] as $key => $value) {
            //         $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);
            //         $list['data'][$key] = $value;
            //     }
            // }
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }

        $xsSourceList = Db::table('crm_source')->select();
        $xsStatusList = Db::table('crm_clues_status')->select();

        View::assign('xsSourceList',$xsSourceList);
        View::assign('xsStatusList',$xsStatusList);
        return View::fetch();
    }

    //(我的线索)列表
    public function perclulist(){
        if($this->request->isPost()){
            $key=input('post.key');
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');

            $list = \think\facade\Db::name('crm_customer')
                ->where(['status'=>0,'issuccess'=>-1])
                ->where(['pr_user'=> $this->admin['username']])
                ->order('ut_time desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
             // 是否有查看手机号的权限
            $userinfo = Db::name('admin')->where('username',$this->admin['username'])->find(); 
            if ($userinfo['isphone'] == 0) {
                foreach ($list['data'] as $key => $value) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);
                    $list['data'][$key] = $value;
                }
            }
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }

        $xsSourceList = Db::table('crm_source')->select();
        $xsStatusList = Db::table('crm_clues_status')->select();

        View::assign('xsSourceList',$xsSourceList);
        View::assign('xsStatusList',$xsStatusList);


        return View::fetch();
    }

    //批量导入，线索上传
    public function xlsUpload(){
        @ini_set("memory_limit",'-1');
        @ini_set('max_execution_time', '0');

        $file = request()->file('xlsFile');
        try {
            validate(['xlsFile'=>'fileSize:209715200|fileExt:xlsx,xls'])->check(['xlsFile'=>$file]);
            // 上传到本地服务器
            $fileSystem=\think\facade\Filesystem::disk('local');
            $savename = $fileSystem->putFile( 'xls', $file,'md5');
            $info=$fileSystem->path($savename);
        } catch (\think\exception\ValidateException $e) {
            $this->error($e->getMessage());
        }


        if (file_exists($info)) {
            $res = importExecl($info);
            if(!$res['code']){
                $this->error($res['msg']);
            }
            $result=$res['data'];
            unset($result[0]); //移除标题
            $insDate=[];
            $i=0;
            foreach ($result as $value){
                //看下手机号是否存在。将存在的手机号保存在数组里。
                $userExist = \think\facade\Db::name('crm_customer')->where('phone', $value['G'])->find();
                if (empty($userExist)){
                    $data=[];
                    $data['xs_name'] = $value['A'];//A线索名称
                    $data['xs_status'] = $value['B'];//B客户状态
                    $data['xs_source'] = $value['C'];//C客户来源
                    $data['xs_area'] = $value['D'];//D 地区
                    $data['kh_hangye'] = $value['E'];//E 行业类别
                    $data['kh_contact'] = $value['F'];//F 联系人
                    $data['phone'] = $value['G'];//G 联系号码
                    $data['kh_rank'] = $value['H'];//H 客户级别
                    $data['kh_status'] = $value['I'];//I 客户状态
                    $data['email'] = $value['J'];//J 邮箱
                    $data['remark'] = $value['K'];//K 备注
                    $data['pr_user'] = $this->admin['username'];
                    $data['ut_time'] =  date("Y-m-d H:i:s",time());
                    $data['at_time'] = date("Y-m-d H:i:s",time());
                    $data['at_user'] = $this->admin['username'];
                    $data['status'] = 0;
                    $insDate[]=$data;
                }else{
                    $i++;
                }
            }

            if($insDate){
                $failcount = count($insDate); //最终的总数
                $insertAll = Db::table('crm_customer')->insertAll($insDate);
                if ($insertAll){
                    $msg='导入'.$failcount.'条数据成功！';
                    if($i){
                        $msg=$msg.'已过滤重复线索信息'.$i.'条!';
                    }
                    $msg = ['code' => 0,'msg'=>$msg,'data'=>[]];
                    return json($msg);
                }else{
                    $msg = ['code' => -200,'msg'=>'线索导入失败！','data'=>[]];
                    return json($msg);
                }
            }else{
                $msg = ['code' => -200,'msg'=>'导入数据失败！,已过滤重复线索信息'.$i.'条!','data'=>[]];
                return json($msg);
            }
        }else{
            $this->error('上传文件保存失败');
        }

    }

//    我的线索导入
    public function myXlsUpload(){
        return $this->xlsUpload();
    }

    //新建线索
    public function add(){
        if($this->request->isPost()){
            $data['xs_name'] = Request::param('xs_name');
            $data['xs_area'] = Request::param('xs_area');
            $data['kh_hangye'] = Request::param('kh_hangye');
            $data['kh_contact'] = Request::param('kh_contact');
            $data['kh_username'] = Request::param('kh_username');
            $data['phone'] = Request::param('phone');

            $data['xs_source'] = Request::param('xs_source');
            $data['xs_status'] = Request::param('xs_status');
            $data['remark'] = Request::param('remark');

            $data['at_user'] = $this->admin['username'];
            $data['at_time'] = date("Y-m-d H:i:s",time());
            $data['ut_time'] = date("Y-m-d H:i:s",time());
            $data['pr_user'] = $this->admin['username'];
            $data['pr_user_bef'] = $this->admin['username'];

            $userExist = \think\facade\Db::name('crm_customer')->where('phone', $data['phone'])->find();
            if ($userExist){
                $msg = ['code' => -200,'msg'=>'抱歉，联系号码重复不可添加！','data'=>[]];
                return json($msg);
            }

            $result = Db::table('crm_customer')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }


        $xsSourceList = Db::table('crm_source')->select();
        $xsStatusList = Db::table('crm_clues_status')->select();
        $xsAreaList = Db::table('crm_clues_area')->select();
        $xsHangyeList = Db::table('crm_client_hangye')->select();
        View::assign('xsHangyeList',$xsHangyeList);
        View::assign('xsAreaList',$xsAreaList);

        View::assign('xsSourceList',$xsSourceList);
        View::assign('xsStatusList',$xsStatusList);

        return View::fetch('clues/add');
    }
    //编辑线索
    public function edit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
            $data['ut_time'] = date("Y-m-d H:i:s",time());

            $result = Db::table('crm_customer')->where(['id'=>$data['id']])->where('status',0)->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }


        $result = Db::table('crm_customer') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);

        $xsSourceList = Db::table('crm_source')->select();
        $xsStatusList = Db::table('crm_clues_status')->select();
        $xsAreaList = Db::table('crm_clues_area')->select();
        $xsHangyeList = Db::table('crm_client_hangye')->select();
        View::assign('xsHangyeList',$xsHangyeList);
        View::assign('xsAreaList',$xsAreaList);
        View::assign('xsSourceList',$xsSourceList);
        View::assign('xsStatusList',$xsStatusList);

        return View::fetch('clues/edit');
    }
    //删除线索
    public function del(){
        $id = Request::param('id');
//        var_dump($id);exit();
        if(is_string($id)){
            $where=['id','=',$id];
        }elseif(is_array($id)){
            $where=['id','in',$id];
        }else{
            $msg = ['code' => -200,'msg'=>'请求参数有误！','data'=>[]];
            return json($msg);
        }

        $result = Db::table('crm_customer')->where([$where])->where('status',0)->delete();

        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }

    //公共线索删除
    public function selectdel(){
        return $this->del();
    }

    //我的线索删除
    public function mydel(){
        $id = Request::param('id');
        if(is_string($id)){
            $where=['id','=',$id];
        }elseif(is_array($id)){
            $where=['id','in',$id];
        }else{
            $msg = ['code' => -200,'msg'=>'请求参数有误！','data'=>[]];
            return json($msg);
        }
        $result = Db::table('crm_customer')->where([$where])->where('status',0)->where('pr_user','=',$this->admin['username'])->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }

    //客户状态
    public function statusList(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_clues_status')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        return View::fetch();
    }
    //添加客户状态
    public function statusAdd(){
        if($this->request->isPost()){
            $data['status_name'] = Request::param('status_name');
            $data['add_time'] = time();
            $result = Db::table('crm_clues_status')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }
        return View::fetch('clues/status_list_add');
    }
    //编辑客户状态
    public function statusEdit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
            $result = Db::table('crm_clues_status')->where(['id'=>$data['id']])->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }


        $result = Db::table('crm_clues_status') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('clues/status_list_edit');
    }
    //删除客户状态
    public function statusDel(){
        $id = Request::param('id');
        $result = Db::table('crm_clues_status')->where('id',$id)->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }





    //客户来源
    public function sourceList(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_source')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        return View::fetch();
    }
    //添加客户来源
    public function sourceAdd(){
        if($this->request->isPost()){
            $data['name'] = Request::param('name');
            $data['add_time'] = time();
            $result = Db::table('crm_source')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }
        return View::fetch('clues/source_list_add');
    }
    //编辑客户来源
    public function sourceEdit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
            $result = Db::table('crm_source')->where(['id'=>$data['id']])->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }


        $result = Db::table('crm_source') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('clues/source_list_edit');
    }
    //删除客户来源
    public function sourceDel(){
        $id = Request::param('id');
        $result = Db::table('crm_source')->where('id',$id)->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }


    //地区来源
    public function areaList(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_clues_area')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        return View::fetch();
    }
    //添加地区来源
    public function areaAdd(){
        if($this->request->isPost()){
            $data['area_name'] = Request::param('area_name');
            $data['add_time'] = time();
            $result = Db::table('crm_clues_area')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }
        return View::fetch('clues/area_list_add');
    }
    //编辑地区来源
    public function areaEdit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
            $result = Db::table('crm_clues_area')->where(['id'=>$data['id']])->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }


        $result = Db::table('crm_clues_area') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('clues/area_list_edit');
    }
    //删除地区来源
    public function areaDel(){
        $id = Request::param('id');
        $result = Db::table('crm_clues_area')->where('id',$id)->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }




    //转成客户
    public function toTurnKh(){

        if ($this->request->isAjax()){
            $data['id']  = Request::param('id');
            $username=Db::table('crm_customer')->where(['id'=>$data['id']])->value('pr_user');
            $map['a.username'] =  $username;
            $max_customers_num=Db::table(config('database.connections.mysql.prefix').'admin')->alias('a')->cache('max_customers_num_'.$username)
                ->join(config('database.connections.mysql.prefix').'auth_group ag','a.group_id = ag.group_id','left')
                ->where($map)
                ->value('ag.max_customers_num');
            if( $max_customers_num > 0){
                //            验证业务员的最大容量
                $cz_c=Db::table('crm_customer')->whereRaw('pr_user=:username AND status=1 AND `issuccess` = -1',['username'=>$username])->count();
                $yx_c=$max_customers_num-$cz_c;
                if($yx_c<=0){
                    $msg=$username.'最大拥有的客户数量已满,如果需要转入客户请先转移部分客户至公海！';
                    $msg = ['code' => -200,'msg'=>$msg,'data'=>[]];
                    return json($msg);
                }

            }
            $data['name']  = Request::param('name');
            $data['kh_rank']  = Request::param('kh_rank');
            $data['kh_status']  = Request::param('kh_status');
            $data['kh_need']  = Request::param('kh_need');
            $data['to_kh_time'] = date("Y-m-d H:i:s",time());
            $data['status'] = 1;//0-线索，1客户，2公海

            $result = Db::table('crm_customer')->where(['id'=>$data['id']])->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'线索转客户成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'抱歉，线索转客户失败！','data'=>[]];
                return json($msg);
            }
        }

        $khRankList = Db::table('crm_client_rank')->select();
        $khStatusList = Db::table('crm_client_status')->select();

        View::assign('khRankList',$khRankList);
        View::assign('khStatusList',$khStatusList);

        $result = Db::table('crm_customer') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('clues/turn_kh');
    }



    //线索搜索
    public function cluesSearch(){
        $page =input('page',1,'intval');
        $limit =input('limit')?input('limit'):config('app.pageSize');
        $keyword = Request::param('keyword');
        $list= $this->model -> getCluesSearchList($page,$limit,$keyword);
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);

    }


    //（我的线索）搜索
    public function personCluesSearch(){
        $page =input('page',1,'intval');
        $limit =input('limit')?input('limit'):config('app.pageSize');
        $keyword = Request::param('keyword');
        $list= $this->model -> getPersonCluesSearchList($page,$limit,$keyword,$this->admin);
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);

    }


    //线索转移，变更负责人
    public function alterPrUser(){

        $ids = Request::param('ids');
        View::assign('ids',$ids);
        //查询所有管理员（去除admin）
        $adminResult = \think\facade\Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('adminResult',$adminResult);

        if ($this->request->isAjax()){
            $username = Request::param('username');
            $idsArr = explode(",",$ids);

            $count = 0;
            foreach ($idsArr as $key => $value){
                $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->value('pr_user');
                $data['pr_user'] = $username;
                $data['id'] = $value;
                $insertAll = Db::name('crm_customer')->update($data);
                if ($insertAll){
                    $count ++;
                }
            }
            if ($count > 0){
                $msg = ['code' => 0,'msg'=>'转移'.$count.'条线索成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'转移失败！','data'=>[]];
                return json($msg);
            }
        }

        return View::fetch('clues/alter_pr_user');
    }


    //线索转移，变更负责人（个人）
    public function alterPrUserPri(){
        //1，获取提交的线索ID 【1,2,3,4,】
        $ids = Request::param('ids');
        View::assign('ids',$ids);


        //查询所有管理员（去除admin）
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('adminResult',$adminResult);

        if ($this->request->isAjax()){
            $username = Request::param('username');
            $idsArr = explode(",",$ids);


            $count = 0;
            foreach ($idsArr as $key => $value){
                $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->value('pr_user');
                $data['pr_user'] = $username;
                $data['id'] = $value;
                $insertAll = Db::name('crm_customer')->update($data);
                if ($insertAll){
                    $count ++;
                }
            }




            if ($count > 0){
                $msg = ['code' => 0,'msg'=>'转移'.$count.'条线索成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'转移失败！','data'=>[]];
                return json($msg);
            }
        }

        return View::fetch('clues/alter_pr_user');
    }

}